package org.jeecg.modules.login.api;

import com.dingtalk.api.response.OapiV2UserGetResponse;
import lombok.SneakyThrows;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.login.LoginService;
import org.jeecg.modules.login.handler.ding.DingMiniProgramHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * [钉钉小程序] 免密登录
 *
 * @author tianyi.jiang
 * @since 1.2.2
 */
@RestController
@RequestMapping("/sys/ding/mp")
@ConditionalOnExpression("'${basicplatform.login.ding-mini-program.enable:false}'.equals('true')")
public class DingMiniProgramLogin {

    private final DingMiniProgramHandler dingMiniProgramHandler;

    private final LoginService loginService;

    @SneakyThrows
    @GetMapping("/auth")
    public Result<?> dingLogin(@RequestParam("code") String code) {
        OapiV2UserGetResponse oapiV2UserGetResponse = dingMiniProgramHandler.passwordFree(code);
        if (oapiV2UserGetResponse.isSuccess()) {
            String mobile = oapiV2UserGetResponse.getResult().getMobile();
            return loginService.auth4DingMiniProgram(mobile);
        }
        throw new JeecgBootException("认证失败！");
    }

    public DingMiniProgramLogin(DingMiniProgramHandler dingMiniProgramHandler, LoginService loginService) {
        this.dingMiniProgramHandler = dingMiniProgramHandler;
        this.loginService = loginService;
    }
}
